package com.wll.okhttpcode;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.IOException;
import java.security.cert.Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.CertificatePinner;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        Peer certificate chain:
//        sha256/+OAwmENjrBT/pI2PSOVO/I3OtHeKk7Y0PH9h8Z2z3Nw=: CN=hencoder.com
//        sha256/YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=: CN=Let's Encrypt Authority X3,O=Let's Encrypt,C=US
//        sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=: CN=DST Root CA X3,O=Digital Signature Trust Co.
//        String hostname = "hencoder.com";
        String hostname = "kyfw.12306.cn/otn/regist/init";

        CertificatePinner certificatePinner = new CertificatePinner.Builder()
                .add(hostname, "sha256/+OAwmENjrBT/pI2PSOVO/I3OtHeKk7Y0PH9h8Z2z3Nw=",
//                        ,"sha256/YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=",
//                        "sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=",
                        "sha256/LdWvHs+KB8hJKizVWHCWq3j+FzpWnr/8Hn0wnWIr5Yk=")
                .build();

        HttpsUtils.SSLParams sslParams = HttpsUtils.getSSLSocketFactory(this);

        OkHttpClient client = null;

        if (sslParams != null) {
            client = new OkHttpClient.Builder()
//                .cache(new Cache())
//                .certificatePinner(certificatePinner)
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            Log.e("hostname", hostname);
                            Log.e("session", "CipherSuite " + session.getCipherSuite()
                                    + "\nPeerHost " + session.getPeerHost()
                                    + "\nProtocol " + session.getProtocol()
                                    + "\nsession " + session.toString());
                            //                            return true;
//                            Certificate[] c = session.getLocalCertificates();
//                            if (c != null && c.length > 0) {
//                                Log.e("LocalCertificates ", String.valueOf(c));
//                            }
//                            Certificate[] c1;
//                            try {
//                                c1 = session.getPeerCertificates();
//                                if (c1 != null && c1.length > 0) {
//                                    Log.e("PeerCertificates ", String.valueOf(c1));
//                                }
//                            } catch (SSLPeerUnverifiedException e) {
//                                e.printStackTrace();
//                            }
                            return true;
                        }
                    })
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    .build();

            Request request = new Request.Builder()
//                .cacheControl()
                    .url("https://" + hostname)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("fail", "12306 " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.e("success", "12306 " + String.valueOf(response));

                }
            });

            Request request1 = new Request.Builder()
//                .cacheControl()
                    .url("https://hencoder.com")
                    .build();

            client.newCall(request1).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("fail", "https://hencoder.com " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.e("success", "https://hencoder.com " + String.valueOf(response));

                }
            });
        }


        //建立连接
//        client.newWebSocket(request, new WebSocketListener() {
//            //当远程对等方接受Web套接字并可能开始传输消息时调用。
//            @Override
//            public void onOpen(WebSocket webSocket, Response response) {
//                super.onOpen(webSocket, response);
//                webSocket.send("发送消息");
//            }
//
//            //当收到文本（类型{@code 0x1}）消息时调用
//            @Override
//            public void onMessage(WebSocket webSocket, String text) {
//                super.onMessage(webSocket, text);
//            }
//
//            //当收到二进制（类型为{@code 0x2}）消息时调用。
//            @Override
//            public void onMessage(WebSocket webSocket, ByteString bytes) {
//                super.onMessage(webSocket, bytes);
//            }
//
//            //当远程对等体指示不再有传入的消息将被传输时调用。
//            @Override
//            public void onClosing(WebSocket webSocket, int code, String reason) {
//                super.onClosing(webSocket, code, reason);
//            }
//
//            //当两个对等方都表示不再传输消息并且连接已成功释放时调用。 没有进一步的电话给这位听众。
//            @Override
//            public void onClosed(WebSocket webSocket, int code, String reason) {
//                super.onClosed(webSocket, code, reason);
//            }
//
//            //由于从网络读取或向网络写入错误而关闭Web套接字时调用。
//            // 传出和传入的消息都可能丢失。 没有进一步的电话给这位听众。
//            @Override
//            public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
//                super.onFailure(webSocket, t, response);
//            }
//        });

    }
}
